#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

import re


MAX_CHECK_SIZE = 8192

# attempt to retrieve a URL from a string
def checkUrl(urlDict,ret = 0):
	# re for verifying URLs
	urlMatch = re.compile(r'[\S\s]*?\s?(((ht|f)tp(s?)://)([\w./?%=&+-_~]{3,1024}))')
	urlOrder = ['mIdentifier', 'mFormat', 'mDescription', 'mType', 'mSource']
	for k in urlOrder:
		if len(urlDict[k]) > MAX_CHECK_SIZE: break
		url = urlMatch.search(urlDict[k])
		if url is not None:
			break
	if url != None:
		# url found
		if ret == 0:
			return 1
		else:
			return url.groups()[0]
	# url not found
	if ret == 0:
		return 0
	else:
		return ''

def linkify(field):
	"""
	Find all links in the field and add anchor tags to them.
	"""
	# re for verifying URLs
	urlMatch = re.compile(r'([\S\s]*?\s?)(((ht|f)tp(s?)://)([\w./?%=&+-_~]+))')

	if len(field) > MAX_CHECK_SIZE: return field
	field = urlMatch.sub('\\1<a href="\\2">\\2</a>',field)
	
	return field
# eof

